#
#  Copyright (C) 2009 GSyC/LibreSoft
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, either version 3 of the License, or
#    (at your option) any later version.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU Affero General Public License for more details.
#
#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
# 
#    Author : Jose Antonio Santos Cadenas <jcaden __at__ gsyc __dot__ es>
#

from operator import or_

from django.contrib.auth.decorators import login_required
from search.forms import SearchForm
from django.shortcuts import render_to_response
from django.template import RequestContext

from search.utils import do_search

from django.contrib.auth.models import User 
from tribes.models import Tribe
from photos.models import Image

def search(request, form_class=SearchForm, template_name="search/search.html"):
    """
    Search in the social network
    """
    search_form = SearchForm(request.REQUEST)
    if search_form.is_valid():
        terms = search_form.cleaned_data['search']
        #Search for people
        fields = ["username"]
        people = do_search(User, fields, terms)
        #Email search must be exact
        people = people or do_search(User, ["emailaddress__email"], terms, True)
        
        #Search for photos
        fields = ["title", "title_slug", "caption"]
        photos = do_search(Image, fields, terms)
        
        #Search for tribes
        fields= ["slug", "name", "description" ]
        tribes = do_search(Tribe, fields, terms)
            
        #Search for tribes 

        return render_to_response(template_name, {
            "search_form": search_form,
            "query"      : True,
            "people"     : people,
            "photos"     : photos, 
            "tribes"     : tribes,
            }, context_instance=RequestContext(request))
    return render_to_response(template_name, {
        "search_form": search_form,
        "query"      : False,
        }, context_instance=RequestContext(request))
search = login_required(search)